import * as vscode from "vscode";
import { exec } from "child_process";

const defaultTerminalName = "cangjieTools";
export class executor {
    static runInTerminal(commandLine: string, terminalName = defaultTerminalName) {
        let curTerm = this.terminals[terminalName];

        if (!curTerm) {
            let existTer = this.tryGet(terminalName);
            if (existTer) {
                curTerm = existTer;
            }

            if (!curTerm) {
                curTerm = vscode.window.createTerminal({
                    name: terminalName
                });
            }

            this.terminals[terminalName] = curTerm;
        }

        if(vscode.window.activeTerminal == curTerm) {
            curTerm.sendText(commandLine);
            curTerm.show();
        } else {
            vscode.window.onDidChangeActiveTerminal(async (terminal) => {
                if (terminal === curTerm) {
                    terminal.sendText(commandLine);
                    curTerm.show();
                }
            });
        }

        vscode.window.onDidCloseTerminal(terminal => {
            if (terminal === curTerm) {
                this.disposeTerminal(terminal.name);
            }
        });

    }

    public static exec(command: string): Promise<string> {
        return new Promise((resolve, reject) => {
            return exec(command, (error, stdout) => {
                if (error) {
                    reject(error.message);
                } else {
                    resolve(stdout);
                }
            });
        });
    }

    public static disposeTerminal(terminal: string = defaultTerminalName): void {
        this.terminals[terminal].dispose();
        delete this.terminals[terminal];
    }

    private static terminals: { [id: string]: vscode.Terminal } = {};

    static tryGet(name: string) {
        let terminals = vscode.window.terminals;
        for (let terminal of terminals) {
            if (terminal.name === name) {
                return terminal;
            }
        }
        return undefined;
    }

}